//
//  NewsTableViewModel.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/10/19.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "NewsTableViewModel.h"

#import "CommonNewsItemViewModel.h"

#import "ArticlesListData.h"

@interface NewsTableViewModel()

@property (nonatomic, readwrite, strong) RACCommand* requestDataCmd;

@property (nonatomic, readwrite, strong) RACCommand* selectCmd;

@end

@implementation NewsTableViewModel

- (void)initialize
{
    [super initialize];
    
    @weakify(self);
    
    self.isReplace = YES;
    
    /// viewDidLoad后加载数据
    self.shouldRequestRemoteDataOnViewDidLoad = YES;
    /// 允许下拉刷新
    self.shouldPullDownToRefresh = NO;
    /// 允许上拉加载
    self.shouldPullUpToLoadMore = NO;
    
    /// 请求数据
    self.requestDataCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id inputInfo) {
        
        @strongify(self);
        
        NSInteger loadIndex = [inputInfo[@"LoadIndex"] integerValue];
        
        return [self requestListDataSignalWithPageIndex:loadIndex pageSize:self.isReplace?2:List_PageSize];
    }];
    
    /// 选中
    self.selectCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id x) {
        @strongify(self);
        
        @weakify(self);
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            @strongify(self);
            
            @weakify(self);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), dispatch_get_main_queue(), ^
            {
                @strongify(self);
                [subscriber sendNext:x];
                [subscriber sendCompleted];
            });
            return nil;
        }];
    }];
    /// 允许并行执行
    self.selectCmd.allowsConcurrentExecution = NO;
}

- (RACSignal *)requestListDataSignalWithPageIndex:(int)pageIndex pageSize:(int)pageSize
{
    @weakify(self)
    
    if (self.isReplace)
    {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            
            @strongify(self);
            
            NSDictionary* postData = interface_param_mainreplace(@2);
            
            @weakify(self);
            return [[AFNetWorkUtils racPOSTWthURL:url_interface_mainreplace params:postData] subscribeNext:^(id x)
                    {
                        @strongify(self)
                        
                        /// 转化数据
                        @weakify(self);
                        
                        ArticlesListData* articlesListData = [ArticlesListData modelWithJSON:x];
                        
                        NSArray *viewModels = [articlesListData.datas.rac_sequence map:^CommonNewsItemViewModel *(ArticleListData* data)
                                               {
                                                   @strongify(self);
                                                   
                                                   CommonNewsItemViewModel *itemViewModel = [[CommonNewsItemViewModel alloc] initWithData:data cellHeight:self.cellHeight];
                                                   
                                                   return itemViewModel;
                                               }].array;
                        
                        self.dataSource = viewModels;
                        
                        [subscriber sendNext:nil];
                        [subscriber sendCompleted];
                    }   error:^(NSError *error) {
                        //错误处理
                        
                        [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:error.userInfo[customErrorInfoKey]}]];
                        [subscriber sendCompleted];
                    }
                    ];
            
            return nil;
        }];
    }
    else
    {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            
            @strongify(self);
            
            NSDictionary* postData = interface_param_getcatelist(self.cateID, self.areaID, @(pageIndex+1), @(pageSize)); 
            
            @weakify(self);
            return [[AFNetWorkUtils racPOSTWthURL:url_interface_getcatelist params:postData] subscribeNext:^(id x)
                    {
                        @strongify(self)
                        
                        /// 转化数据
                        @weakify(self);
                        
                        ArticlesListData* articlesListData = [ArticlesListData modelWithJSON:x];
                        
                        NSArray *viewModels = [articlesListData.datas.rac_sequence map:^CommonNewsItemViewModel *(ArticleListData* data)
                                               {
                                                   @strongify(self);
                                                   
                                                   CommonNewsItemViewModel *itemViewModel = [[CommonNewsItemViewModel alloc] initWithData:data cellHeight:self.cellHeight];
                                                   
                                                   return itemViewModel;
                                               }].array;
                        
                        if (viewModels == nil || viewModels.count < pageSize)
                        {
                            self.lastPage = self.page;
                            
                            if (viewModels == nil)
                                viewModels = @[];
                        }
                        else
                        {
                            self.lastPage = 999;
                        }
                        
                        if (self.shouldPullUpToLoadMore)
                        {
                            if (0 == pageIndex)
                            {
                                self.dataSource = viewModels;
                            }
                            else
                            {
                                if (self.dataSource == nil)
                                {
                                    self.dataSource = viewModels;
                                }
                                else
                                {
                                    self.dataSource = [self.dataSource arrayByAddingObjectsFromArray:viewModels];
                                }
                            }
                        }
                        else
                        {
                            self.dataSource = viewModels;
                        }
                        
                        [subscriber sendNext:nil];
                        [subscriber sendCompleted];
                    }   error:^(NSError *error) {
                        //错误处理
                        
                        [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:error.userInfo[customErrorInfoKey]}]];
                        [subscriber sendCompleted];
                    }
                    ];
            
            return nil;
        }];
    }
}

@end
